import type { AsideControlProps } from '../control/components/AsideControl.vue'
import { checkTogglePowerAccessable } from '@/controller/common/ErrorHandler/validator'
import type { BaseController } from '@/controller/BaseAppliance/definition'
import type { PowerOutageController } from '@/controller/common/PowerOutage/definition'

export function useShutdown(
  control: BaseController.Control | (BaseController.Control & PowerOutageController.Control)
) {
  const isOnline = computed(() => control.store.isOffline === false)
  /**
   * 电源控制
   */
  const powerControlOverwrites = computed<Partial<AsideControlProps> | null>(() => {
    if (!control.store.shouldConfirmShutdown) return null
    return {
      actived: isOnline.value,
      tipText: null,
    }
  })
  function onPowerChange() {
    // 前置判断 (是否支持远程控制等)
    const accessable = checkTogglePowerAccessable(control)
    if (!accessable) return

    // 需要确认断电的设备 且 当前为在线状态，由确认弹框触发断电
    if (control.store.shouldConfirmShutdown && isOnline.value) {
      showShutdownTips.value = true
      return
    }

    // 直接触发开关机
    control.store.togglePowerState()
  }

  /**
   * 断电
   */
  const showShutdownTips = ref(false)
  function confirmShutdown() {
    showShutdownTips.value = false
    return control.store.shutdown()
  }

  return {
    powerControlOverwrites,
    onPowerChange,
    // 断电
    showShutdownTips,
    confirmShutdown,
  }
}
